const vscode = require('vscode');
const fs = require('fs').promises;
const path = require('path');
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
const { glob } = require('glob');

/**
 * 代理工具集，提供AI用于完成用户任务的核心工具
 */
class AgentTools {
    constructor(workspaceRoot) {
        this.workspaceRoot = workspaceRoot;
        this.activeTasks = new Map();
        // 添加变更跟踪
        this.pendingChanges = new Map(); // 存储未确认的文件变更
    }

    // 重置所有待确认的变更
    resetPendingChanges() {
        // 删除所有临时差异文件
        this.pendingChanges.forEach(async (change, filePath) => {
            const fullPath = path.join(this.workspaceRoot, filePath);
            const tempOriginalPath = `${fullPath}.original`;
            const tempNewPath = `${fullPath}.new`;
            
            // 尝试删除临时文件
            try {
                await fs.unlink(tempOriginalPath).catch(() => {});
                await fs.unlink(tempNewPath).catch(() => {});
                console.log(`清除临时差异文件: ${filePath}`);
            } catch (err) {
                // 忽略错误
            }
        });
        
        // 清空变更Map
        this.pendingChanges.clear();
        console.log('重置所有待确认的变更');
        
        // 通知前端
        vscode.commands.executeCommand('xinye.resetFileChanges');
        
        return {
            success: true,
            message: '所有待确认的变更已重置'
        };
    }

    // 写入文件
    async writeToFile(filePath, content) {
        try {
            const fullPath = path.join(this.workspaceRoot, filePath);
            
            // 确保目录存在
            await this.ensureDirectoryExists(path.dirname(fullPath));
            
            // 检查文件是否已存在
            let originalContent = '';
            try {
                originalContent = await fs.readFile(fullPath, 'utf8');
            } catch (err) {
                // 文件不存在，使用空字符串
            }
            
            // 创建或更新差异视图
            await this.showDiffView(filePath, originalContent, content);
            
            // 添加到待确认变更
            this.addPendingChange(filePath, originalContent, content, 'write');
            
            // 临时写入文件以便查看
            await fs.writeFile(fullPath, content);
            
            // 打开文件供用户查看
            this.openFile(fullPath);
            
            return {
                success: true,
                message: `文件已创建，等待确认: ${filePath}`,
                filePath: filePath,
                isPending: true
            };
        } catch (error) {
            return {
                success: false,
                error: `写入文件失败: ${error.message}`,
                filePath: filePath
            };
        }
    }

    // 读取文件
    async readFile(filePath) {
        try {
            const fullPath = path.join(this.workspaceRoot, filePath);
            const content = await fs.readFile(fullPath, 'utf8');
            return {
                success: true,
                content,
                filePath: filePath
            };
        } catch (error) {
            return {
                success: false,
                error: `读取文件失败: ${error.message}`,
                filePath: filePath
            };
        }
    }

    // 在文件中替换文本
    async replaceInFileWithDiff(filePath, oldText, newText) {
        try {
            const readResult = await this.readFile(filePath);
            if (!readResult.success) {
                return readResult;
            }

            const content = readResult.content;
            
            // 1. 标准化文本以处理不同的换行符和空白字符
            const normalizeText = (text) => {
                return text
                    .replace(/\r\n/g, '\n')  // 统一换行符
                    .replace(/\t/g, '    ');  // 将制表符转换为空格
            };
            
            const normalizedContent = normalizeText(content);
            const normalizedOldText = normalizeText(oldText);
            
            // 2. 检查标准化后的内容是否包含要替换的文本
            if (!normalizedContent.includes(normalizedOldText)) {
                console.log('精确匹配失败，尝试替代方法');
                
                // 3. 对于短文本（例如函数名、变量名），尝试更精确的匹配
                if (oldText.length < 50) {
                    // 为简短文本创建一个更精确的正则表达式
                    const escapedOldText = oldText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                    
                    // 添加单词边界，确保匹配整个标识符而不是部分标识符
                    // 例如：'mian' 应该匹配 'int mian()' 而不是 'domain'
                    let wordPattern;
                    
                    // 对于函数名，查找包含括号的模式
                    if (oldText.includes('(') && oldText.includes(')')) {
                        // 保留原始模式，因为已经很具体
                        wordPattern = new RegExp(escapedOldText, 'g');
                    } else {
                        // 对于变量名或其他标识符，添加单词边界
                        wordPattern = new RegExp(`\\b${escapedOldText}\\b`, 'g');
                    }
                    
                    // 尝试找到匹配
                    const matches = normalizedContent.match(wordPattern);
                    if (matches && matches.length > 0) {
                        console.log(`找到短文本精确匹配: ${matches[0]}`);
                        const newContentWithReplacement = normalizedContent.replace(wordPattern, newText);
                        
                        // 显示差异
                        await this.showDiffView(filePath, content, newContentWithReplacement);
                        
                        // 添加到待确认变更
                        this.addPendingChange(filePath, content, newContentWithReplacement, 'replace');
                        
                        // 临时应用变更
                        const fullPath = path.join(this.workspaceRoot, filePath);
                        await fs.writeFile(fullPath, newContentWithReplacement);
                        
                        return {
                            success: true,
                            message: `文件替换等待确认: ${filePath}`,
                            filePath: filePath,
                            isPending: true
                        };
                    }
                    
                    // 对于函数定义，尝试匹配更宽松的模式
                    if (oldText.includes('(') || oldText.trim().endsWith(')')) {
                        // 函数名可能在某些空格或者其他字符周围
                        const functionNamePattern = oldText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
                            .replace(/\s+/g, '\\s*'); // 允许空格变化
                        const funcPattern = new RegExp(functionNamePattern, 'g');
                        
                        // 尝试匹配函数模式
                        const funcMatches = normalizedContent.match(funcPattern);
                        if (funcMatches && funcMatches.length > 0) {
                            console.log(`找到函数模式匹配: ${funcMatches[0]}`);
                            const newContentWithFuncReplacement = normalizedContent.replace(funcPattern, newText);
                            
                            // 显示差异
                            await this.showDiffView(filePath, content, newContentWithFuncReplacement);
                            
                            // 添加到待确认变更
                            this.addPendingChange(filePath, content, newContentWithFuncReplacement, 'replace');
                            
                            // 临时应用变更
                            const fullPath = path.join(this.workspaceRoot, filePath);
                            await fs.writeFile(fullPath, newContentWithFuncReplacement);
                            
                            return {
                                success: true,
                                message: `文件替换等待确认: ${filePath}`,
                                filePath: filePath,
                                isPending: true
                            };
                        }
                    }
                    
                    // 对于类似"int mian()"这样的函数定义，尝试只匹配函数名
                    if (oldText.includes(' ') && oldText.includes('(')) {
                        // 提取函数名部分
                        const matches = oldText.match(/\s+(\w+)\s*\(/);
                        if (matches && matches[1]) {
                            const funcName = matches[1];
                            // 文件中查找这个函数名
                            const funcNamePattern = new RegExp(`\\b${funcName}\\s*\\(`, 'g');
                            
                            // 如果新文本也有类似模式，提取新函数名
                            const newMatches = newText.match(/\s+(\w+)\s*\(/);
                            if (newMatches && newMatches[1]) {
                                const newFuncName = newMatches[1];
                                
                                // 在原文本中查找匹配
                                const funcMatches = normalizedContent.match(funcNamePattern);
                                if (funcMatches && funcMatches.length > 0) {
                                    console.log(`找到函数名匹配: ${funcMatches[0]}, 替换为: ${newFuncName}`);
                                    
                                    // 替换整个函数定义
                                    // 先找到函数声明行
                                    const lines = normalizedContent.split('\n');
                                    let modifiedLines = [];
                                    
                                    for (let i = 0; i < lines.length; i++) {
                                        if (lines[i].match(funcNamePattern)) {
                                            // 替换这一行中的函数名
                                            modifiedLines.push(lines[i].replace(funcName, newFuncName));
                                        } else {
                                            modifiedLines.push(lines[i]);
                                        }
                                    }
                                    
                                    const newContentWithNameReplacement = modifiedLines.join('\n');
                                    
                                    // 显示差异
                                    await this.showDiffView(filePath, content, newContentWithNameReplacement);
                                    
                                    // 添加到待确认变更
                                    this.addPendingChange(filePath, content, newContentWithNameReplacement, 'replace');
                                    
                                    // 临时应用变更
                                    const fullPath = path.join(this.workspaceRoot, filePath);
                                    await fs.writeFile(fullPath, newContentWithNameReplacement);
                                    
                                    return {
                                        success: true,
                                        message: `文件替换等待确认: ${filePath}`,
                                        filePath: filePath,
                                        isPending: true
                                    };
                                }
                            }
                        }
                    }
                }
                
                // 4. 处理多余的空白字符
                const cleanText = (text) => text.replace(/\s+/g, ' ').trim();
                const cleanContent = cleanText(normalizedContent);
                const cleanOldText = cleanText(normalizedOldText);
                
                if (!cleanContent.includes(cleanOldText)) {
                    // 5. 尝试匹配前后40个字符的上下文
                    console.log('模糊匹配失败，尝试部分内容匹配');
                    
                    // 如果oldText超过80个字符，只取前40个字符和后40个字符
                    let partialMatch = false;
                    if (normalizedOldText.length > 80) {
                        const start = normalizedOldText.substring(0, 40);
                        const end = normalizedOldText.substring(normalizedOldText.length - 40);
                        
                        // 查找起始内容的位置
                        const startPos = normalizedContent.indexOf(start);
                        if (startPos >= 0) {
                            // 在找到的起始位置附近查找结束内容
                            const searchArea = normalizedContent.substring(startPos);
                            const endPos = searchArea.indexOf(end);
                            
                            if (endPos > 0 && endPos < normalizedOldText.length * 2) {
                                // 找到了起始和结束部分，提取中间内容
                                const extractedText = normalizedContent.substring(startPos, startPos + endPos + end.length);
                                console.log(`找到部分匹配，长度为 ${extractedText.length}`);
                                
                                // 比较一下原文本长度与提取文本长度，判断是否合理匹配
                                const lengthDiff = Math.abs(extractedText.length - normalizedOldText.length);
                                if (lengthDiff <= normalizedOldText.length * 0.2) { // 允许20%的长度差异
                                    // 在原内容中替换提取的文本
                                    const newContent = content.replace(extractedText, newText);
                                    
                                    // 显示差异
                                    await this.showDiffView(filePath, content, newContent);
                                    
                                    // 添加到待确认变更
                                    this.addPendingChange(filePath, content, newContent, 'replace');
                                    
                                    // 临时应用变更
                                    const fullPath = path.join(this.workspaceRoot, filePath);
                                    await fs.writeFile(fullPath, newContent);
                                    
                                    return {
                                        success: true,
                                        message: `文件替换等待确认: ${filePath}`,
                                        filePath: filePath,
                                        isPending: true
                                    };
                                }
                            }
                        }
                    }
                    
                    // 6. 添加更多详细的错误信息帮助排查
                    console.log(`替换失败详情:
                        - 原文本长度: ${oldText.length}
                        - 原文本预览: ${oldText.substring(0, Math.min(50, oldText.length))}
                        - 文件内容长度: ${content.length}
                        - 文件类型: ${path.extname(filePath)}
                    `);
                    
                    // 所有尝试失败
                    return {
                        success: false,
                        error: `文件中找不到要替换的文本`,
                        filePath: filePath,
                        details: {
                            oldTextLength: oldText.length,
                            contentLength: content.length,
                            oldTextPreview: oldText.length > 100 ? `${oldText.substring(0, 50)}...${oldText.substring(oldText.length-50)}` : oldText
                        }
                    };
                } else {
                    // 模糊匹配成功，替换所有匹配项
                    console.log('模糊匹配成功');
                    const regex = new RegExp(cleanOldText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
                    const newContentResult = normalizedContent.replace(regex, normalizedOldText);
                    
                    // 显示差异
                    await this.showDiffView(filePath, content, newContentResult);
                    
                    // 添加到待确认变更
                    this.addPendingChange(filePath, content, newContentResult, 'replace');
                    
                    // 临时应用变更
                    const fullPath = path.join(this.workspaceRoot, filePath);
                    await fs.writeFile(fullPath, newContentResult);
                    
                    return {
                        success: true,
                        message: `文件替换等待确认: ${filePath}`,
                        filePath: filePath,
                        isPending: true
                    };
                }
            }
            
            // 精确匹配成功，直接替换
            console.log('精确匹配成功');
            const newContent = content.replace(oldText, newText);
            
            // 显示差异
            await this.showDiffView(filePath, content, newContent);
            
            // 添加到待确认变更
            this.addPendingChange(filePath, content, newContent, 'replace');
            
            // 临时应用变更
            const fullPath = path.join(this.workspaceRoot, filePath);
            await fs.writeFile(fullPath, newContent);
            
            return {
                success: true,
                message: `文件替换等待确认: ${filePath}`,
                filePath: filePath,
                isPending: true
            };
            
        } catch (error) {
            console.error(`替换文件内容失败:`, error);
            return {
                success: false,
                error: `替换文件内容失败: ${error.message}`,
                filePath: filePath
            };
        }
    }
    
    // 显示差异视图方法
    async showDiffView(filePath, originalContent, newContent) {
        try {
            const fullPath = path.join(this.workspaceRoot, filePath);
    
            // 创建临时URI用于显示差异
            const tempOriginalUri = vscode.Uri.file(`${fullPath}.original`);
            const tempNewUri = vscode.Uri.file(`${fullPath}.new`);
    
            // 写入内容到临时文件
            await fs.writeFile(tempOriginalUri.fsPath, originalContent);
            await fs.writeFile(tempNewUri.fsPath, newContent);
    
            // 显示差异
            await vscode.commands.executeCommand(
                'vscode.diff',
                tempOriginalUri,
                tempNewUri,
                `差异预览: ${path.basename(filePath)}`
            );
    
            return true;
        } catch (error) {
            console.error('创建差异视图失败:', error);
            return false;
        }
    }
    
    // 添加跟踪变更的方法
    addPendingChange(filePath, originalContent, newContent, operation = 'write') {
        // 计算变更行数
        const changeInfo = this.calculateChangeStats(originalContent, newContent);
        
        this.pendingChanges.set(filePath, {
            filePath,
            originalContent,
            newContent,
            operation,
            timestamp: Date.now(),
            changeInfo
        });
        
        // 通知变更
        this.notifyFileChange(filePath, operation, changeInfo);
    
                return {
                    success: true,
            filePath,
            isPending: true,
            operation,
            changeInfo
        };
    }
    
    // 计算变更行数统计
    calculateChangeStats(originalContent, newContent) {
        if (!originalContent && !newContent) return { added: 0, removed: 0 };
        
        // 处理undefined或null
        const origContent = originalContent || '';
        const newCont = newContent || '';
        
        const originalLines = origContent.split('\n');
        const newLines = newCont.split('\n');
        
        const originalLineCount = originalLines.length;
        const newLineCount = newLines.length;
        
        console.log(`计算行数变更 - 原始行数: ${originalLineCount}, 新行数: ${newLineCount}`);
        
        // 基本行数变更计算
        let added = 0;
        let removed = 0;
        
        if (newLineCount > originalLineCount) {
            added = newLineCount - originalLineCount;
        } else if (originalLineCount > newLineCount) {
            removed = originalLineCount - newLineCount;
        }
        
        // 如果是新文件，所有行都是添加的
        if (!originalContent && newContent) {
            added = newLineCount;
            removed = 0;
        }
        
        // 如果是删除文件，所有行都是删除的
        if (originalContent && !newContent) {
            added = 0;
            removed = originalLineCount;
        }
        
        console.log(`行数变更结果 - 增加: ${added}, 删除: ${removed}`);
        
                return {
            added: added,
            removed: removed
        };
    }

    // 确认变更
    async confirmChange(filePath) {
        if (!this.pendingChanges.has(filePath)) {
            return { success: false, error: `没有待确认的变更: ${filePath}` };
        }
        
        const change = this.pendingChanges.get(filePath);
        
        // 临时文件路径
        const fullPath = path.join(this.workspaceRoot, filePath);
        const tempOriginalPath = `${fullPath}.original`;
        const tempNewPath = `${fullPath}.new`;
        
        // 删除临时文件
        try {
            await fs.unlink(tempOriginalPath);
            console.log(`成功删除临时文件: ${tempOriginalPath}`);
        } catch (err) {
            // 忽略不存在的文件
            console.log(`删除临时文件失败或文件不存在: ${tempOriginalPath}`, err.message);
        }
        
        try {
            await fs.unlink(tempNewPath);
            console.log(`成功删除临时文件: ${tempNewPath}`);
        } catch (err) {
            // 忽略不存在的文件
            console.log(`删除临时文件失败或文件不存在: ${tempNewPath}`, err.message);
        }
        
        // 文件已经临时写入了，只需要移除跟踪
        this.pendingChanges.delete(filePath);
        
        // 通知变更已确认
        this.notifyFileChangeConfirmed(filePath, change.operation);
        
            return {
            success: true,
            message: `文件变更已确认: ${filePath}`
        };
    }
    
    // 拒绝变更
    async rejectChange(filePath) {
        if (!this.pendingChanges.has(filePath)) {
            return { success: false, error: `没有待确认的变更: ${filePath}` };
        }
        
        const change = this.pendingChanges.get(filePath);
        const fullPath = path.join(this.workspaceRoot, filePath);
        
        // 临时文件路径
        const tempOriginalPath = `${fullPath}.original`;
        const tempNewPath = `${fullPath}.new`;
        
        // 删除临时文件
        try {
            await fs.unlink(tempOriginalPath);
            console.log(`成功删除临时文件: ${tempOriginalPath}`);
        } catch (err) {
            // 忽略不存在的文件
            console.log(`删除临时文件失败或文件不存在: ${tempOriginalPath}`, err.message);
        }
        
        try {
            await fs.unlink(tempNewPath);
            console.log(`成功删除临时文件: ${tempNewPath}`);
        } catch (err) {
            // 忽略不存在的文件
            console.log(`删除临时文件失败或文件不存在: ${tempNewPath}`, err.message);
        }
        
        // 如果是新建文件且原内容为空，则删除文件
        if (change.operation === 'write' && !change.originalContent) {
            try {
                await fs.unlink(fullPath);
                console.log(`删除新创建的文件: ${fullPath}`);
            } catch (err) {
                // 忽略不存在的文件
                console.log(`尝试删除文件失败或文件不存在: ${fullPath}`, err.message);
            }
        } else {
            // 恢复原始内容
            await fs.writeFile(fullPath, change.originalContent);
            console.log(`恢复文件内容: ${fullPath}`);
        }
        
        // 移除跟踪
        this.pendingChanges.delete(filePath);
        
        // 通知变更已拒绝
        this.notifyFileChangeRejected(filePath);
        
        return {
            success: true,
            message: `文件变更已拒绝: ${filePath}`
        };
    }
    
    // 通知文件变更
    notifyFileChange(filePath, operation, changeInfo) {
        vscode.commands.executeCommand('xinye.notifyFileChange', {
            filePath,
            operation,
            changeInfo
        });
    }
    
    // 通知变更确认
    notifyFileChangeConfirmed(filePath, operation) {
        vscode.commands.executeCommand('xinye.notifyFileChangeConfirmed', {
            filePath,
            operation
        });
        }
    
    // 通知变更拒绝
    notifyFileChangeRejected(filePath) {
        vscode.commands.executeCommand('xinye.notifyFileChangeRejected', {
            filePath
        });
    }

    // 搜索文件
    async searchFiles(pattern, directory = '', recursive = true) {
        try {
            const basePath = directory ? path.join(this.workspaceRoot, directory) : this.workspaceRoot;
            
            // 添加安全检查，确保搜索路径在工作区内
            const normalizedBasePath = path.normalize(basePath);
            const normalizedWorkspace = path.normalize(this.workspaceRoot);
            if (!normalizedBasePath.startsWith(normalizedWorkspace)) {
                return {
                    success: false,
                    error: '安全限制：搜索路径必须在工作区内'
                };
            }

            const searchPattern = recursive ? '**/*' : '*';
            const filePattern = new RegExp(pattern, 'i');
            
            // 使用glob查找所有文件，添加额外的安全选项
            const files = await glob(searchPattern, { 
                cwd: basePath,
                nodir: true,
                absolute: false,  // 不返回绝对路径
                follow: false,    // 不跟踪符号链接
                dot: false        // 不包含点文件（如 .git）
            });
            
            // 过滤文件内容
            const results = [];
            for (const file of files) {
                const filePath = path.join(directory, file);
                // 再次验证文件路径
                const fullPath = path.join(this.workspaceRoot, filePath);
                const normalizedPath = path.normalize(fullPath);
                if (!normalizedPath.startsWith(normalizedWorkspace)) {
                    console.warn(`跳过工作区外的文件: ${filePath}`);
                    continue;
                }

                try {
                    const content = await fs.readFile(fullPath, 'utf8');
                    if (filePattern.test(content)) {
                        results.push({
                            path: filePath,
                            matches: this.extractMatches(content, pattern)
                        });
                    }
                } catch (err) {
                    console.warn(`无法读取文件 ${filePath}: ${err.message}`);
                }
            }
            
            return {
                success: true,
                results,
                count: results.length,
                searchPath: directory || '工作区根目录' // 添加搜索路径信息
            };
        } catch (error) {
            return {
                success: false,
                error: `搜索文件失败: ${error.message}`
            };
        }
    }

    // 列出目录中的文件
    async listFiles(directory = '', recursive = false) {
        try {
            const basePath = directory ? path.join(this.workspaceRoot, directory) : this.workspaceRoot;
            
            const entries = await fs.readdir(basePath, { withFileTypes: true });
            const files = [];
            
            for (const entry of entries) {
                const entryPath = path.join(directory, entry.name);
                
                if (entry.isFile()) {
                    files.push({
                        path: entryPath,
                        type: 'file'
                    });
                } else if (entry.isDirectory()) {
                    files.push({
                        path: entryPath,
                        type: 'directory'
                    });
                    
                    if (recursive && !this.shouldIgnoreDirectory(entry.name)) {
                        const subDirFiles = await this.listFiles(entryPath, true);
                        if (subDirFiles.success) {
                            files.push(...subDirFiles.files);
                        }
                    }
                }
            }
            
            return {
                success: true,
                files,
                directory
            };
        } catch (error) {
            return {
                success: false,
                error: `列出文件失败: ${error.message}`,
                directory
            };
        }
    }

    // 执行终端命令
    async executeCommand(command) {
        try {
            // 创建或获取终端
            let terminal = vscode.window.terminals.find(t => t.name === 'Xing Ye');
            if (!terminal) {
                terminal = vscode.window.createTerminal('Xing Ye');
            }
            
            // 显示终端
            terminal.show();
            
            // 切换到工作目录
            terminal.sendText(`cd "${this.workspaceRoot}"`);
            
            // 执行命令
            terminal.sendText(command);
            
            // 使用 exec 来获取命令执行结果
            const { stdout, stderr } = await exec(command, { cwd: this.workspaceRoot });
            
            return {
                success: true,
                stdout,
                stderr: stderr || undefined,
                message: '命令已在终端中执行'
            };
        } catch (error) {
            return {
                success: false,
                error: error.message,
                stderr: error.stderr,
                message: '命令执行失败'
            };
        }
    }

    // 创建目录
    async createDirectory(dirPath) {
        try {
            const fullPath = path.join(this.workspaceRoot, dirPath);
            await this.ensureDirectoryExists(fullPath);
            return {
                success: true,
                message: `目录创建成功: ${dirPath}`,
                dirPath: dirPath
            };
        } catch (error) {
            return {
                success: false,
                error: `创建目录失败: ${error.message}`,
                dirPath: dirPath
            };
        }
    }

    // 删除文件
    async deleteFile(filePath) {
        try {
            const fullPath = path.join(this.workspaceRoot, filePath);
            
            // 首先检查文件是否存在
            try {
                await fs.access(fullPath);
            } catch (e) {
                return {
                    success: false,
                    error: `文件不存在: ${filePath}`,
                    filePath: filePath
                };
            }
            

            
            await fs.unlink(fullPath);
            return {
                success: true,
                message: `文件删除成功: ${filePath}`,
                filePath: filePath
            };
        } catch (error) {
            return {
                success: false,
                error: `删除文件失败: ${error.message}`,
                filePath: filePath
            };
        }
    }

    // 重命名文件
    async renameFile(oldPath, newPath) {
        try {
            const fullOldPath = path.join(this.workspaceRoot, oldPath);
            const fullNewPath = path.join(this.workspaceRoot, newPath);
            
            // 确保目标目录存在
            await this.ensureDirectoryExists(path.dirname(fullNewPath));
            
            // 重命名文件
            await fs.rename(fullOldPath, fullNewPath);
            
            return {
                success: true,
                message: `文件重命名成功: ${oldPath} -> ${newPath}`,
                oldPath: oldPath,
                newPath: newPath
            };
        } catch (error) {
            return {
                success: false,
                error: `重命名文件失败: ${error.message}`,
                oldPath: oldPath,
                newPath: newPath
            };
        }
    }

    // 辅助方法

    // 确保目录存在
    async ensureDirectoryExists(dirPath) {
        try {
            await fs.mkdir(dirPath, { recursive: true });
        } catch (error) {
            if (error.code !== 'EEXIST') {
                throw error;
            }
        }
    }


    // 打开文件
    openFile(filePath) {
        const uri = vscode.Uri.file(filePath);
        vscode.window.showTextDocument(uri);
    }

    // 从文件内容中提取匹配项
    extractMatches(content, pattern) {
        const regex = new RegExp(pattern, 'g');
        const matches = [];
        const lines = content.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            let match;
            while ((match = regex.exec(line)) !== null) {
                matches.push({
                    line: i + 1,
                    text: match[0],
                    context: this.getLineContext(lines, i)
                });
            }
        }
        
        return matches;
    }

    // 获取行上下文
    getLineContext(lines, lineIndex, contextSize = 2) {
        const start = Math.max(0, lineIndex - contextSize);
        const end = Math.min(lines.length - 1, lineIndex + contextSize);
        
        const context = [];
        for (let i = start; i <= end; i++) {
            context.push({
                line: i + 1,
                text: lines[i],
                isCurrent: i === lineIndex
            });
        }
        
        return context;
    }

    // 检查是否应忽略目录
    shouldIgnoreDirectory(dirName) {
        const ignoreDirs = ['.git', 'node_modules', '.vscode', 'dist', 'build'];
        return ignoreDirs.includes(dirName);
    }

    // 搜索文本内容
    async searchText(text, filePattern = '*', directory = '', recursive = true) {
        try {
            const basePath = directory ? path.join(this.workspaceRoot, directory) : this.workspaceRoot;
            
            // 添加安全检查，确保搜索路径在工作区内
            const normalizedBasePath = path.normalize(basePath);
            const normalizedWorkspace = path.normalize(this.workspaceRoot);
            if (!normalizedBasePath.startsWith(normalizedWorkspace)) {
                return {
                    success: false,
                    error: '安全限制：搜索路径必须在工作区内'
                };
            }

            const searchPattern = recursive ? '**/' + filePattern : filePattern;
            
            // 使用glob查找匹配的文件
            const files = await glob(searchPattern, { 
                cwd: basePath,
                nodir: true,
                absolute: false,
                follow: false,
                dot: false
            });
            
            // 在文件内容中搜索指定的文本
            const results = [];
            for (const file of files) {
                const filePath = path.join(directory, file);
                const fullPath = path.join(this.workspaceRoot, filePath);
                const normalizedPath = path.normalize(fullPath);
                if (!normalizedPath.startsWith(normalizedWorkspace)) {
                    console.warn(`跳过工作区外的文件: ${filePath}`);
                    continue;
                }

                try {
                    const content = await fs.readFile(fullPath, 'utf8');
                    if (content.includes(text)) {
                        // 计算文本在文件中的行号
                        const lines = content.split('\n');
                        const occurrences = [];
                        
                        for (let i = 0; i < lines.length; i++) {
                            if (lines[i].includes(text)) {
                                occurrences.push({
                                    line: i + 1,
                                    context: this.getLineContext(lines, i)
                                });
                            }
                        }
                        
                        results.push({
                            path: filePath,
                            occurrences
                        });
                    }
                } catch (err) {
                    console.warn(`无法读取文件 ${filePath}: ${err.message}`);
                }
            }
            
            return {
                success: true,
                results,
                count: results.length,
                searchText: text,
                searchPath: directory || '工作区根目录'
            };
        } catch (error) {
            return {
                success: false,
                error: `搜索文本失败: ${error.message}`
            };
        }
    }

    // 向用户展示选项
    async showOptionsToUser(options, message = "请选择一个选项") {
        try {
            // 确保选项是数组格式
            if (typeof options === 'string') {
                // 尝试将逗号分隔的字符串转换为数组
                options = options.split(',').map(opt => opt.trim());
            } else if (!Array.isArray(options) || options.length === 0) {
                options = ["选项1", "选项2", "选项3"];
                console.warn("选项格式无效，使用默认选项", options);
            }
            
            // 不再使用vscode API直接显示选项，而是返回选项数据
            // 让AgentTask将options和message发送到前端显示
            return {
                success: true,
                message: "准备显示选项",
                options: options,
                displayMessage: message || "请选择一个选项"
            };
        } catch (error) {
            return {
                success: false,
                error: `显示选项失败: ${error.message}`
            };
        }
    }
}

module.exports = AgentTools; 